package com.demo.gulimall.product.exception;

import com.demo.gulimall.common.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * 统一异常处理类
 * @author Chen Yuan
 * @create 2023-05-24  16:28
 */
@RestControllerAdvice
public class ExceptionControllerAdvice {

	/**
	 * JSR303 异常统一处理
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public R handleVaildException(MethodArgumentNotValidException exception){
		BindingResult bindingResult = exception.getBindingResult();
		HashMap<String, String> resMap = new HashMap<>();
		// 遍历校验出错的字段
		for (FieldError fieldError : bindingResult.getFieldErrors()) {
			// 获取错误信息
			String defaultMessage = fieldError.getDefaultMessage();
			// 获取出错的字段名
			String field = fieldError.getField();
			resMap.put(field, defaultMessage);
		}
		return R.error(resMap.toString());
	}
}
